﻿
#pragma once
#pragma endregion 
#include "afxinet.h"
#include "CFiltration.h"                //过滤规则
#include "ComPort1.h"                   //串口1 
#include "CameraList.h"                 //相机列表
#include "MessageShm.h"                 //共享内存 
#include "MvCodeReaderCtrl.h"           //智能相机
#include "MvCodeReaderErrorDefine.h"    //智能相机
#include "MvCodeReaderParams.h"         //智能相机
#include "MvCodeReaderPixelType.h"      //智能相机
#include "MVIDCodeReader.h"             //海康工业相机动态库   
#include "MVIDCodeReaderDefine.h"       //海康工业相机宏、变量定义
#include "Other.h"                      //自定义常用函数类
#include "resource.h"                   //界面控件ID
#include "Settings.h"                   //自定义设置信息
#include <list>                         //列表   
#include <mutex>                        //锁
#include <cmath>                        //包含std::abs 
#include <opencv2/opencv.hpp>  
#include <boost/asio.hpp>                //tcp
#include <boost/array.hpp>               //tcp
#include "Container.h" 
#include "EditPrintf.h"
#include "turbojpeg.h"                                  //智能相机JPEG 
#if _MSC_VER >= 1900
#pragma comment(lib, "legacy_stdio_definitions.lib")    //智能相机
#include "LogisticsBase/CApi/CApiLogisticsBaseInterface.h" //华睿智能相机
#include <io.h> //输入输出 
#endif    
using namespace std;
using namespace Gdiplus;    //GDI界面
//using namespace HUALOG;     //日志
using namespace boost::asio;
#define ImgBufNum                   20      //存图缓存数量
/// <summary>
/// 动态界面
/// </summary> 
#define IDC_ComboBox_Camera         7000    // 范围10000-10099
#define IDC_Check_Camera            7100    // 范围10100-10199
#define IDC_Picture_Camera          7200    // 范围10200-10399 
//线程ID
#define Tid_Ftp1Con                 10101
#define Tid_Tcp0Con                 10102
#define Tid_Tcp1Con                 10103
#define Tid_Tcp2Con                 10104
#define Tid_Tcp3Con                 10105
#define Tid_Tcp5Con                 10145
#define Tid_SaveImage               10106
#define Tid_Camera0Rct              10108
#define Tid_Camera1Rct              10109
#define Tid_ZhongWeiRct             10110 
#define Tid_DaemonProcess1          10112
#define Tid_DaemonProcess2          10113
#define Tid_MessageShm1             10114
#define Tid_Hik1Channel             10115
#define Tid_ShowOutPut              10116
#define Tid_NetworkCardIp           10117
#define Tid_CameraState             10118
#define Tid_PeriodicDel1            10119
#define Tid_PeriodicDel2            10120

#define Tid_Init                    10200
#define Tid_PredictionTray          10201
#define Tid_TrayAndCode             10202
    
#define Tid_UpLoadImage1            10307
#define Tid_UpLoadImage2            10308

#define Tid_Tcp4Con                 11051
#define Tid_Tcp6Con                 11053
#define Tid_Tcp7Con                 11054
#define Tid_Http1Con                11091 
#define Tid_Udp1Con                 11095  
#define Tid_Udp2Con                 11096
#define Tid_UartCon                 11072
#define Tid_ConUart3                11073
#define Tid_Watermark               11061
/// <summary>
// 智能相机
/// </summary> 
typedef struct _MV_CODEREADER_DRAW_PARAM_   // 图像展示结构体
{
    HDC hDC;
    unsigned char* pData; 
    int nImageWidth;
    int nImageHeight; 
    int nWndRectWidth;
    int nWndRectHeight;
    int nDstX;
    int nDstY;

}MV_CODEREADER_DRAW_PARAM;
// 解压JPG图像输出结构体
typedef struct _MV_CODEREADER_TJPG_PARAM_
{
    unsigned char*  pBufInput;
    unsigned int    nBufInputLen;
    unsigned int    nWidth;
    unsigned int    nHeight;
    unsigned int    nJpgQuality;
    unsigned char*  pBufOutput;
    unsigned int    nBufOutputLen;

}MV_CODEREADER_TJPG_PARAM;
//图像缓存
typedef struct
{
    uint8_t*        data;
    uint32_t		dataSize;
    int32_t			width;
    int32_t			height;
    int32_t			type;
    uint32_t		img_idx;
    int32_t         codeNum;
    double  		x[256][4]{};
    double  		y[256][4]{};
}RunResult;
 
#pragma pack(2)
#pragma pack() 
static uint8_t         ImgBufNext;                  //存图缓存索引
static unsigned char   ImgBuf[ImgBufNum][20000000]; //存图缓存 20000000
 

class AtCodeMasterDlg : public CDialogEx   //AtovoCodeMasterDlg 对话框
{

#pragma region 默认
    /// <summary>
    /// 默认
    /// </summary>
#ifdef AFX_DESIGN_TIME
    enum { IDD = IDD_AtCodeMaster };
#endif
private: 
    CToolTipCtrl m_Ttc;                                 //鼠标悬停提示 
    void SetToolTipsMsgMap();                           //鼠标悬停提示
protected:
    HICON                   h_Icon;                     //主窗体句柄
    virtual void DoDataExchange(CDataExchange* pDX);	//DDX/DDV 支持 
    virtual BOOL OnInitDialog();
    //初次进入页面
    void OnTimer(UINT_PTR nIDEvent);                    //定时器 
    void ReSize(void);                                  //对所有控件进行布局
    void OnPaint();                                     //如果向对话框添加最小化按钮，则需要下面的代码 
    HCURSOR OnQueryDragIcon();                          //当用户拖动最小化窗口时系统调用此函数取得光标
    DECLARE_MESSAGE_MAP()
public:
    int Initial();                                      //初次进入页面配置
    std::mutex mtxDataDirMutex;
    bool RegularFileDeletion(CString FilePath, int Day);
private:
    BOOL                    InitialStart = true;        //第一次打开软件
    void SaveGetIniSaves();                             //保存
    void OnClose();                                     //窗体销毁后
    void SaveGetIni();                                   
    void OnDestroy();                                   //窗口即将销毁 
    void ThreadRun(unsigned int ID);                    //开启指定线程 
public:
    AtCodeMasterDlg(CWnd* pParent = nullptr);
    ~AtCodeMasterDlg();
    CString                 AppPath ;                   //程序根目录
    CString                 ini_pth ;                   //程序根目录

    void GetConfigRegExp();                             //读取过滤规则
    void GetConfig();                                   //读取配置文件
    void Init();                                        //初次启动在线程里面的
    void NetworkCardIp();                               //获取网卡IP
    void exception_state(const string& deviceDescribe, const string& deviceType, const string& faultDescribe, const string& faultType, const string& monitorEndTime, const uint8_t& monitorLevel, const string& monitorTime, const uint8_t& monitorType);
    void CloseAllApp();                                 //关闭所有程序
    void GetConfig1();                                  //
public:
#define RegNum   10
    bool Reg_AutoCheck[RegNum];
    string Reg_AutoAppId[RegNum];
    string Reg_AutoKey[RegNum];
    string Reg_AutoUrl[RegNum];
    bool   Reg_Check[RegNum];
    string Reg_Name[RegNum];
    string Reg_Key[RegNum];
    string Reg_Exp[RegNum];
#pragma endregion

#pragma region 界面 
    /// <summary>
    /// 界面
    /// </summary> 
private:
    void                    Uicontrol001();                     //创建控件

    BOOL                    Color_Blue;                         //蓝色
    BOOL                    Color_Red;                          //红色
    POINT                   old;                                //窗口位置坐标
    POINT                   oldTab;                             //窗口位置坐标 
    HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor);    //字体颜色和大小
    void OnSize(UINT nType, int cx, int cy);                    //窗体大小发生变化 
    int CreateWindowHandle(void* pUser);                        //创建图像显示窗口句柄
    bool IsDisplay[MaxDeviceNum] = { true };                    //是否显示相机画面 
    afx_msg void OnBnClickedCamera0();                          //是否显示相机画面0
    afx_msg void OnBnClickedCamera1();                          //是否显示相机画面1
    afx_msg void OnBnClickedCamera2();                          //是否显示相机画面2
    afx_msg void OnBnClickedCamera3();                          //是否显示相机画面3
public:
    afx_msg void OnNMClickListParam(NMHDR* pNMHDR, LRESULT* pResult);//算法参数,值发生变化
    afx_msg void OnLButtonDblClk(UINT nFlags, CPoint point);        //双击图像界面最大化
    /// <summary>
    /// 子窗体、菜单栏
    /// </summary>  
private:
    EditPrintf             pr = new EditPrintf;  //输出子窗体 
public:
    Settings                Set;                //设置参数
    Other                   Oth;                //其它常用函数 
    DeviceList              Dev;                //设备列表
    CFiltration             Cfi;                //快递接口参数
    uint8_t                 At_mode;            //模式0=顶扫模式，1=补码模式
    bool                    last_ok=true;       //补码模式下上一单状态 0=可继续扫码
    uint8_t                 last_t;             //补码模式下上一单状态 0=可继续扫码
    int64_t                 TimeZone;//时区-ms
    uint8_t                 last_t_max;         //补码模式-超时时间
    void OnUpdate32773(CCmdUI* pCmdUI);         //过滤规则
    void OnUpdate32774(CCmdUI* pCmdUI);         //设置
    void OnUpdate32805(CCmdUI* pCmdUI);         //输出
    void OnUpdate32775(CCmdUI* pCmdUI);         //添加相机
    void OnUpdate32776(CCmdUI* pCmdUI);         //日志
    void OnUpdate32777(CCmdUI* pCmdUI);         //图片查询
    void OnUpdate32778(CCmdUI* pCmdUI);         //扫码记录查询
    void OnUpdate32795(CCmdUI* pCmdUI);         //清消息 
    void OnUpdate32796(CCmdUI* pCmdUI);         //连接相机数量
    void OnUpdate32797(CCmdUI* pCmdUI);         //TCP1连接
    void OnUpdate32798(CCmdUI* pCmdUI);         //TCP2连接 
    void OnUpdate32799(CCmdUI* pCmdUI);         //FTP连接 
    void OnUpdate32803(CCmdUI* pCmdUI);         //数量清零 
    void OnUpdate32804(CCmdUI* pCmdUI);         //Post测试
    void OnUpdate32781(CCmdUI* pCmdUI);         //多相机画面9
    void OnUpdate32782(CCmdUI* pCmdUI);         //多相机画面9
    void OnUpdate32784(CCmdUI* pCmdUI);         //多相机画面9
    void OnUpdate32786(CCmdUI* pCmdUI);         //多相机画面9
    void OnUpdate32789(CCmdUI* pCmdUI);         //多相机画面9
    void OnUpdate32800(CCmdUI* pCmdUI);         //其它版本
    void OnUpdate32801(CCmdUI* pCmdUI);         //帮助
    void OnUpdate32810(CCmdUI* pCmdUI);         //软触发
    void OnUpdate32811(CCmdUI* pCmdUI);         //图片扫描
    void OnBnClickedBtnalgorithm();             //算法参数页面按钮
    void OnBnClickedBtnprint1();                //输出1页面按钮 
#pragma endregion
#pragma region 相机 
    /// <summary>
    /// 工业相机
    /// </summary>
private:
    void*                   Hik0_h[MaxDeviceNum];      //设备句柄地址
    void*                   c_dis[MaxDeviceNum];            // ch:显示窗口句柄 | en:Handle of display window 
    int                     m_nItem;                        // 刚编辑的行
    int                     m_nSubItem;                     // 刚编辑的列
    CEdit                   C0_AlgorithmInt;                //设置算法Int型参数
    CComboBox               m_comBox;                       //生产单元格下拉列表对象
    BITMAPINFO*             m_bBitmapInfo{};                // 位图信息头
    MVID_PROC_PARAM*        C0_PstProcParam{};              //相机算法参数设置
    std::map<CString, int>  C0_AlgoritMapParam;             //相机算法参数列表
    MVID_CAM_OUTPUT_INFO*   C0_PstOutput[MaxDeviceNum]{};   //采用超时机制获取图像缓存
    CEdit                   m_ctrlExposureEdit;
    CEdit                   m_ctrlGainEdit;
    CEdit                   m_ctrlFrameRateEdit;
    unsigned int            m_nLastImageLen;
    LANGID                  SystemLanguageId;   //语言版本区分
    BOOL PreTranslateMessage(MSG* pMsg);        //处理键盘和鼠标消息

private:
    //列表显示:单号,总耗时,帧号,触发时间,相机IP,聚焦得分,条码类型,识别次数,PPM,状态
    std::deque<std::tuple<string, int16_t, unsigned int,uint64_t,string, unsigned int, string>> queTechwebCode[MaxDeviceNum];
    std::deque<std::tuple<string, uint64_t, uint16_t,uint8_t>> queTechwebBind; //单号、触发时间、托盘、供包台ID
    std::map<string, uint16_t> mapTechwebImg1;
    std::map<string, string  > mapTechwebImg2;
    std::map<string, string> mapTechwebUpImg;
    mutex mtxTechwebCode[MaxDeviceNum];
    mutex mtxTechwebBind;
    mutex mtxTechwebImg;
    mutex mtxTechwebUpImg;
    //绑定：单号,触发时间,包台ID,托盘(备用不准),托盘状态
    std::deque<std::tuple<string, uint64_t, uint8_t, uint16_t, string>> queBindingCode;
    mutex mtxBindingCode;
    //绑定：托盘,时间,包台ID
    std::deque<std::tuple<int16_t, uint64_t, uint8_t>> queBindingTray[MaxDeviceNum];
    mutex mtxBindingTray[MaxDeviceNum];
    //大字体显示条码 
    deque<string> queMaxStrCode;  
    mutex mtxMaxStrCode;

    //绑定
    uint8_t     wDog_Udp1 = 0;          //多久未收到托盘
    uint16_t    wDog_Code1 = 0;         //多久未收到条码
    uint16_t    next_pluse_s[MaxDeviceNum], speed_s[MaxDeviceNum];    //预存上一次
    uint16_t    tray_over_time[MaxDeviceNum] = { 9999,9999,9999,9999,9999 };
    //按钮                                                           
    void AllCameraCodesStart();             //读码按钮               
    void Hik0_CamStart();                   //读码                   
    void Hik0_CamStop();                    //停止读码               
    void OnBnClickedGetParameterButton();   //参数获取按钮           
    void Hik0_GetParameter();               //参数获取-工业相机      
    void OnBnClickedSetParameterButton();   //参数设置按钮           
    void Hik0_SetParameter(uint8_t state);  //工业相机参数设置按钮    
    //图片识别
    typedef struct tagBmpFile
    {
        BITMAPFILEHEADER    stBmpFileHeader;    // ch:文件头结构 | en:File header structure
        BITMAPINFOHEADER    stBmpInfoHeader;    // ch:信息头结构 | en:Information header structure
        unsigned int        nLineBytes;         // ch:行字节宽度 | en:Width of line byte
        RGBQUAD* pstPalette;                    // ch:调色板 | en:Palette
        unsigned char* pBuf;                    // ch:图像数据缓存 | en:Buffer for saving image data
        unsigned int        nBufSize;           // ch:缓存空间大小 | en:Buffer size
    }BmpFile;   //BMP图像文件
    void*                   hImgScanner;
    BmpFile                 m_stBmpFile;    //BMP图像
    MVID_PROC_PARAM*        m_pstProcParam;     //原始图像信息
    CString                 m_strImageFilePath;
    void ReadBmp(CString pchBmpName, BmpFile* pstBmpFile);// ch:读取BMP图像文件 | en:Read the BMP image file
    void ImageScannerPath();    //图片识别-获取图像 
    void ImageScanner();        //图像识别
    //其它
    void UpdatelListCtrl();                 //更新列表 
    void ShowEdit(NM_LISTVIEW* pEditCtrl);  //编辑算法参数列表
    void OnKillfocusEdit();                 //动态生成编辑框失去焦点响应函数
    int InitListCtrl();                     //相机算法参数获取
    void ShowErrorMsg(CString csMessage, int nErrorNum);             //显示错误信息 
    void Display(uint8_t num, int16_t all_time, void* hWnd, MVID_CAM_OUTPUT_INFO* pstDisplayImage, CString Bandwidth, BOOL NetMbps, string dis_text, uint8_t emSize, int DivideTop, string* state); //条码画框
    void DisplayTexts(void* hWnd, string s_Text, int DivideTop, float fHeightProportion, float fWidthProportion); //图像上显示文本                                                                   
#pragma endregion

    /// <summary>
    /// 输出
    /// </summary>
private:
    CListCtrl               ListPrint1;                     //输出 
    CEdit                   editItem;                    //输出 
    uint16_t                noread_n =0;                    //数量-未识别
    uint32_t                Code_Num = 0;                   //数量-发送
    uint32_t                out_num = 0;                    //数量-输出
    uint32_t                SaveImgNum = 0;                 //数量-存图
    uint32_t                WatermarkNum = 0;               //数量-水印
    uint32_t                UpImageNumber = 0;              //数量-传图
    uint32_t                C_All_Num = 0;                  //数量-有条码 
    uint32_t                noread_num = 0;                 //数量:灰度仪统计识别率-noread,nobar
    uint32_t                c_num = 0;                      //数量:灰度仪统计识别率-正常识别
    
    uint32_t                BindingNum = 0;                 //数量-绑定
    uint16_t                BindingFailNum = 0;             //数量-绑定失败数量
    uint16_t                ImgNameTrayNum = 0;             //数量-存图名称加托盘失败数量

    bool                    CheckMuCodeFs = 0;              //合并输出
    string                  MuCodeFs;                       //多条码分隔符
    string                  OutPutStr;                      //扫码输出格式
    string                  img_n_type;                     //图片名称 
public:
    void CameraState();                     //相机状态
    void Printf(CString str);               //打印    
    void print_a(uint8_t ux, const char* format, ...);
    void print_b(uint8_t ux, const char* format, ...);
    void PeriodicDel1();                     //定期删除文件 
    void PeriodicDel2();                     //定期删除文件 
    /// <summary>
    /// 存图传图
    /// </summary>
private:
    //存图
    string                  ImageAllPathType;       //存图全路径输出格式
    MVID_IMAGE_TYPE         ImgSaveType = MVID_IMAGE_JPEG;  //格式
    uint8_t                 DisplayTim[MaxDeviceNum]{ 0 };  //有条码的显示延迟 
    uint8_t                 ImgQuality = 75;      //存图质量
    uint8_t                 ImageQuality2 = 75;     //传图压缩质量
    UINT                    ImageRepetition = 200;  //多供包台存图去重
    BOOL                    MoreRepetition = false; //多供包台去重标志位,TRUE:重复 FALSE:不重复
    CString                 SaveImagePath{};        //设置存图路径
    string                  SaveImgPth{};           //设置存图路径
    string                  SaveImgPth2{};          //存图目录2-备用
    CString                 LogPth{};               //日志路径
    uint16_t                pixel_width;            //像素宽
    uint16_t                pixel_height;           //像素宽
    uint16_t                HFOV;                   //视野宽
    uint16_t                VFOV;                   //视野高
    float                   tray_speed = 0;         //速度
    //图片,图片长,图片宽,图片高,格式,单号数量,单号,存图时间,供包台ID,相机IP,句柄,托盘,状态
    std::deque<std::tuple<unsigned char*, uint64_t, unsigned short, unsigned short, int, uint8_t, string, uint64_t, int16_t, uint8_t, string, void*, uint8_t, string, string>> queImage[MaxDeviceNum];

    mutex                   mtxImage5[MaxDeviceNum]; 
    //水印
    std::deque<std::tuple<string, string, string, string, uint64_t>> queWatermark; // 条码,全目录,时间,托盘 
    std::deque<std::tuple<string, string, string, string, uint64_t >> queWatermark1;// 条码,全目录,时间,托盘,拍照时间 -带绑定信息的
    std::deque<std::tuple<string, string >> queWatermark2;// 条码,绑定信息 -带绑定信息的
    std::deque<string> queWaterFlg; //水印是否加好,再传图
   
    std::deque<std::tuple<string, uint64_t, uint16_t, uint8_t, string, string>> queImgName; //单号对应的托盘- 单号、触发时间、托盘、供包台ID、分拣信息、绑定状态
    std::map<string, string> w1_b_bindImg;   // 分拣信息 
    //TCP传图
    std::deque<std::tuple<unsigned char*, unsigned short, unsigned short, unsigned short>> t_ImgBuf11;

    uint32_t                Laps=0;
    //ftp传图
    //绑定：托盘,时间,目录,图片名称
    std::deque<std::tuple<string, uint64_t, string, string>> queUploadImg[3];
    mutex mtxUploadImg[3];
    list<CString>           ImagePathList;       //传图路径
    list<CString>           ImageNameList;       //传图名称 
    list<CString>           ImagePathList1;      //传图路径1
    list<CString>           ImageNameList1;      //传图名称1

    list<CString>           ImagePathListSto;    //STO传图路径
    list<CString>           ImageNameListSto;    //STO传图名称 
    list<CString>           ImagePathListSto1;   //STO传图路径1
    list<CString>           ImageNameListSto1;   //STO传图名称1 
    uint8_t                 c_repeat_t = 0;      //去重时间
    float                   CodeRepeatTimeSet;   //去重设置时间
    list<string>            repeat;              //条码存入列表-去重 
    list<string>            CodeList;            //条码列表
    list<CString>           CodeIpList;          //IP+条码+时间 
    list<CString>           techweb_l;           //IP+条码+时间 显示用
    list<CString>           CodeTimeList;        //IP+条码+时间列表
 
    /// <summary>
    /// 线程
    /// </summary> 
private:
    bool                    t_AllState = 1;     // 线程while循环标志位
    bool                    print_check[8];     // 界面输出勾选   
    bool                    print_hex[8];     // 界面输出16进制勾选   

public:
    void Camera1CodeReading0();             //解码线程
    void Camera1CodeReading1();             //解码线程
    void Camera1CodeReading2();             //解码线程
    void Camera1CodeReading3();             //解码线程 
    void ImageCallBackA0(MVID_CAM_OUTPUT_INFO* pstOutput, uint8_t num); //海康工业相机回调
    void ImageCallBackA1(MVID_CAM_OUTPUT_INFO* pstOutput, uint8_t num); //海康工业相机回调
    void ImageCallBackA2(MVID_CAM_OUTPUT_INFO* pstOutput, uint8_t num); //海康工业相机回调
    void ImageCallBackA3(MVID_CAM_OUTPUT_INFO* pstOutput, uint8_t num); //海康工业相机回调 
    void ImageCallBackA4(MVID_CAM_OUTPUT_INFO* pstOutput, uint8_t num);
    void ImageCallBackA5(MVID_CAM_OUTPUT_INFO* pstOutput, uint8_t num);
    void ExceptionCallBack0(unsigned int nMsgType,uint8_t num);  //海康工业相机异常回调 
    void ExceptionCallBack1(unsigned int nMsgType,uint8_t num);  //海康工业相机异常回调 
    void ExceptionCallBack2(unsigned int nMsgType,uint8_t num);  //海康工业相机异常回调 
    void ExceptionCallBack3(unsigned int nMsgType,uint8_t num);
    void ExceptionCallBack4(unsigned int nMsgType, uint8_t num);
    void ExceptionCallBack5(unsigned int nMsgType, uint8_t num);
    void InterfaceMaxDisplay();                         //大字体显示
    //海康工业相机异常回调 
    void InterfaceDisplay();
    void drawStringAndSave(const std::string& inputFile, const std::string& outputFile, const std::string& text, int x, int y);//将字符串绘制到图像上并保存为新的JPG文件
    uint8_t hSaveImgNum=0;
    uint8_t hWatermarkNum=0;
    void hSaveImg(uint16_t tray, string sort, string code, string img_pth4, string img_pth4_2, string img_name4, unsigned char* img_data, int img_width, int img_height,
    uint8_t camera, int channels,int img_type, uint64_t img_len, void* NowHandler, uint64_t TiggerTime, int ImageQuality);
    //界面显示
    void SaveImg2Thretad();         //存图2线程-test 
    void WatermarkThretad();
    void hWatermark(string a_path1, string b_code, string b_sort1, string a_time1, uint64_t tiggerTime);
    void UpLoadImage1();             //FTP传图线程
    void UpLoadImage2();             //FTP传图线程
    void Camera1SaveImagePath(CString CodeStr, unsigned char* Buf, MV_CODEREADER_IMAGE_OUT_INFO_EX2* InfoEx2, void* Handle);// 获取图像转换信息-智能相机

    /// <summary>
    /// 设置
    /// </summary>
public:
    bool                    CaptureMode = 1;            //采集模式 0：超时方式获取图片， 1：回调函数方式
    int64_t                 Overtime = 50;              //触发时间补偿
    bool                    SaveImageCheck = 1;         //存图片勾选
    //bool                    NoreadSaveImage;           //noread存图勾选
    bool                    NoBarSlaveImage = 0;        //nobar存图勾选
    bool                    SaveImageCheck2 = 0;        //存图片勾选
    bool                    Ftp1Check = 1;              //FTP发送图片勾选
    CString                 FtpPath;                    //本地目录
    bool                    Tcp0_Check = 0;             //TCP0勾选
    int8_t                  ImageSaveDay = 1;           //图片保存天数.
    CString                 ImageWatermark;             //存图水印内容
    bool                    CheckWatermark;             //加水印勾选
    int                     LogSaveDay = 7;             //日志保存天数
    int                     WaitingTime = 300;           //解码超时
    bool                    PlaySoundCheck = 1;         //是否播放音效 
    string                  BurstMode_str;
    string                  Lightcontrol;
    uint8_t                 LineSelector;
    BOOL                    ProcessCheck = 0;           //是否守护进程1
    uint16_t                HeartbeatInterval = 3000;   //心跳间隔
    int                     HeartbeatMax = 5;           //最大丢包数
    CString                 ProcessPath;                //要守护进程的目录 
    BOOL                    ProcessCheck2 = FALSE;      //是否守护进程2
    int                     HeartbeatInterval2 = 3000;  //检测间隔2
    CString                 ProcessPath2;               //要守护进程的目录2
#pragma region TCP 
    /// <summary>
    /// TCP客户端
    /// </summary>
public:
    void TcpReadClient1(const boost::system::error_code& error, std::size_t bytes_transferred);
    void ReadUdpClient1(const boost::system::error_code& error, std::size_t bytes_transferred);
    void ParsingProtocol_1(char* buf, uint16_t len);
    void ParsingProtocol_2(char* buf, uint16_t len);
    void ParsingProtocol_3(char* buf, uint16_t len);
    void StartUdpClient1();
    void ReadUdpClient2(const boost::system::error_code& e, std::size_t bytes_transferred);    //UDP2回调函数
    void StartUdpClient2(); //UDP2 连接 
    void StartTcpClient1();
    void TcpReadClient2(const boost::system::error_code& error, std::size_t bytes_transferred);
    void StartTcpClient2();
    /// TCP1
    void ReadTcp1(const boost::system::error_code& error, std::size_t bytes_transferred);
    void Read_sTcp1(const std::string& k, const boost::system::error_code& error, std::size_t bytes_transferred);
    void AcceptTcp1(const boost::system::error_code& error, boost::asio::ip::tcp::socket socket, size_t ux);
    void StartTcp1();
    /// TCP3
    void ReadTcp3(const boost::system::error_code& error, std::size_t bytes_transferred);
    void Read_sTcp3(const std::string& k, const boost::system::error_code& error, std::size_t bytes_transferred);
    void AcceptTcp3(const boost::system::error_code& error, boost::asio::ip::tcp::socket socket, size_t ux);
    void StartTcp3();
    void h_tcp4(const boost::system::error_code& error, std::size_t bytes_transferred);
    void RunTcp4();
    /// TCP5 
    void SendTcp_str(uint8_t ux, const std::string& data);
    void SendTcp1(uint8_t ux, const char* format, ...);
    void SendTcpImage(uint8_t ux, const unsigned char* data, size_t dataSize);
    void SendUdpClient(uint8_t ux, const std::string& data);
    void CloseUdp(uint8_t ux);
    void CloseTcp(uint8_t ux);
public:
    //狂扫 
    int16_t                 t_Trans = 300;          //传输耗时 
    bool                    ForecastFlag = false;   //预测标志位
    int                     IntervalTime;           //托盘间隔时间
    uint8_t                 IntervalMeanNum = 30;   //托盘间隔时间平均值取样数量
    uint16_t                IntervalTimeMean = 565; //托盘间隔时间平均值
    int                     IntervalTimeList[100];  //托盘间隔时间list
#pragma endregion

    /// <summary>
    /// 守护进程
    /// </summary>
private:
    time_t                  _dtHeart = 0;   //心跳计时器
    void HeartBeat();                       //发送心跳
    CString RunTime();                      //软件运行时间  
    void DaemonProcess();                   //Tcp+守护进程  
    BOOL ProcessRunning1(CString m_szName); //判断进程是否在运行
    bool Camera0Rec = false;                //工业相机重连标志
    bool Camera1Rec = false;                //智能相机重连标志
    bool Camera3Rec = false;                //智能相机重连标志
    bool ZhongWeiRecFlag = false;           //中科微至相机重连标志
    MessageShm  hMessageShm;    //共享内存
public:
    void LogSaves(char const* LogName, const char* format, ...);
    void LogSavesXls(char const* LogName, const char* format, ...);
    //日志 
    void DaemonProcess2();                  //守护进程 
    void DaemonProcess1();                  //守护进程
    BOOL GetMessage_Str();                  //读取共享内存
    void Camera0Reconnect();                //工业相机重连
    void Camera1Reconnect();                //智能相机重连
    void ZhongWeiReconnect();               //中科微至相机重连
#pragma region FTP客户端
    /// <summary>
    /// FTP客户端
    /// </summary>
private: 
    typedef struct FileItem //保存文件信息
    {
        int nItem = 0;				//在列表框中的索引
        BOOL ifDir = FALSE;         //是文件夹？
        CString strFileName = NULL;	//文件名
    }FILEITEM;
    bool                    Ftp_ConStatus = false;          //Ftp连接状态
    CListCtrl	            Ftp_RemoteFilesList;            //远程文件列表
    CListCtrl	            Ftp_LocalFilesList;             //本地文件列表
    CComboBox	            Ftp_ComboBoxC1;                 //组合框
    CInternetSession*       Ftp_pInetSession = NULL;        //会话对象 
    CFtpConnection*         Ftp_pConnection = NULL;	        //连接对象
    CFtpFileFind*           m_pRemoteFinder = NULL;		    //远程查找文件对象
    CFileFind               m_LocalFinder;			        //本地查找文件对象
    CString                 m_strLocalParentRoot = _T("");	//本地文件目录的上上一层目录
    CString                 m_strRemoteParentRoot = _T(""); //远程文件目录的上上一层目录
    CArray<FILEITEM, FILEITEM&>m_arrLocalFiles;	            //保存本地文件信息
    CArray<FILEITEM, FILEITEM&>m_arrRemoteFiles;            //保存远程文件信息
    bool UpFileImage(CString ImagePath, CString ImageName); //FTP传图
    BOOL Ftp_CreateFolder(CString strFtpPath);              //FTP多级目录创建 
    void Ftp_DownFileAll();                                 //下载所有选中文件
    void Ftp_DownFileOne(FILEITEM fileItem);                //下载单个文件
    void Ftp_UpFileOne(FILEITEM fileItem);                  //上传单个文件
    void SetListCtrlStyle(CListCtrl* pLstCtrl);             //设置列表控件CListCtrl的风格
    void OnRemoteUp();                                      //远程文件上一层目录
    void OnRemoteDownd();                                   //远程文件下一层目录
    void OnSelchangeCombo1();                               //显示获取到的文件
    void Ftp_UpFileAll();                                   //上传所有选中文件
    void Ftp_BrowseDir(CString strDir, CListCtrl* pLstCtrl, CFileFind* pFinder, CArray<FILEITEM, FILEITEM&>* pFilesArr);//获取FTP服务器目录
 public:
    void FtpOnConnect();                                //FTP连接 
#pragma endregion 
    /// <summary>
    /// 串口
    /// </summary>
protected:
    ComPort1                A1_CSerialPort;             //串口对象  
    bool                    A1_OpenComm();              //打开串口 
    LRESULT                 A1_OnCommRxchar(WPARAM wParam, LPARAM lParam); //串口监听 
    //串口是否打开 
    void                    Usart2Send(uint8_t ux, std::string data);
    void                    Usart2Close(uint8_t ux);
public:
    void                    UartConnect();              //打开串口 
    void                    ConnectUart3();             //打开串口A3
    void Uart2HandleRead(const error_code& error, std::size_t bytes_transferred);
    void Uart3HandleRead(const error_code& error, std::size_t bytes_transferred);
    /// <summary>
    /// 智能相机
    /// </summary>
private:
    void*                               Hik1_h[MaxDeviceNum];                // 设备句柄地址 
    UINT8                               Hik1_ChannelNum;                     // 流通道个数
    bool                                Hik1_MscCamera;                      // 是否是多通道相机
    int64_t                             Hik1_MaxImgSize;                     // 图像最大尺寸  
    unsigned int                        Hik1_RunMode;                        // 相机运行模式
    unsigned int                        Hik1_OutRawChannel;                  // RAW模式出图的流通道 
    MV_CODEREADER_DEVICE_INFO_LIST      Hik1_DeviceInfoList;                 // 设备信息列表
    MV_CODEREADER_DEVICE_INFO           Hik1_DeviceInfo;                     // 设备信息
    MV_CODEREADER_IMAGE_OUT_INFO_EX2*   Hik1_PstImgInfoEx2[MaxDeviceNum];    // 图像信息
    MV_CODEREADER_DRAW_PARAM            Hik1_StParam[MaxDeviceNum];          // 输出图像的结构体 
    MV_CODEREADER_TJPG_PARAM            Hik1_PstParam[MaxDeviceNum];         // 解压JPG图像输出结构体 
    unsigned char*                      Hik1_pcDataBuf[MaxDeviceNum];        // 存储图像数据 
    MV_CODEREADER_IMAGE_OUT_INFO_EX2*   Hik1_ImageInfo{ 0 };                 // 最先保存图像信息-智能相机
    unsigned char*                      Hik1_FirstImageBuf{ 0 };             // 最先保存图像数据-智能相机
    int InitResources();                    //初始化必要的资源  
    void Hik1_GetParameter();               //参数获取-智能相机
    void Hik1_SetParameter(uint8_t state);  //智能相机参数设置 
    int Hik1_CamStart();                    //开始采集 
    void DeInitResources();                 //初始化资源  
    int Hik1_CamStop(void);                 //退出相机
    int GetCurrentConfigurationInformation();//获取运行模式、触发模式
    int Draw(MV_CODEREADER_DRAW_PARAM* pstParam);   // 位图信息头  
    int MvJpgDecompress(IN OUT MV_CODEREADER_TJPG_PARAM* pstParam);// jpg解码 
    unsigned int InnerDrawShape(Graphics* g, float x, float y, float w, float h, float fAngle); //条码边缘画矩形
 
    int C1_Display(uint8_t num, int16_t all_time, void* hWnd, unsigned char* pData, MV_CODEREADER_IMAGE_OUT_INFO_EX2* pstDisplayImage, CString Bandwidth, bool NetMbps, string dis_text, uint8_t emSize, int DivideTop, string* state);
    afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
public:
    void Camera1ImageCallBackA0(unsigned char* pData, MV_CODEREADER_IMAGE_OUT_INFO_EX* pFrameInfo, void* pUser);
    void Camera1ImageCallBackB0(unsigned char* pData, MV_CODEREADER_IMAGE_OUT_INFO* pFrameInfo, void* pUser);
    void Camera1ImageCallBack0(unsigned char* pData, MV_CODEREADER_IMAGE_OUT_INFO_EX2* pstOutput, uint8_t num, void* pUser);// ch:注册图像回调处理函数 | en:Registe Call Back
    void Camera1ImageCallBack1(unsigned char* pData, MV_CODEREADER_IMAGE_OUT_INFO_EX2* pstOutput, uint8_t num, void* pUser);// ch:注册图像回调处理函数 | en:Registe Call Back
    void Camera1ImageCallBack2(unsigned char* pData, MV_CODEREADER_IMAGE_OUT_INFO_EX2* pstOutput, uint8_t num, void* pUser);// ch:注册图像回调处理函数 | en:Registe Call Back
    void Camera1ImageCallBack3(unsigned char* pData, MV_CODEREADER_IMAGE_OUT_INFO_EX2* pstOutput, uint8_t num, void* pUser);// ch:注册图像回调处理函数 | en:Registe Call Back
    void Camera1ImageCallBack4(unsigned char* pData, MV_CODEREADER_IMAGE_OUT_INFO_EX2* pstOutput, uint8_t num, void* pUser);// ch:注册图像回调处理函数 | en:Registe Call Back
    void Camera1ImageCallBack5(unsigned char* pData, MV_CODEREADER_IMAGE_OUT_INFO_EX2* pstOutput, uint8_t num, void* pUser);// ch:注册图像回调处理函数 | en:Registe Call Back
    void Camera1ExceptionCallBack0(unsigned int nMsgType, uint8_t num);//异常回调
    void Camera1ExceptionCallBack1(unsigned int nMsgType, uint8_t num);//异常回调
    void Camera1ExceptionCallBack2(unsigned int nMsgType, uint8_t num);//异常回调
    void Camera1ExceptionCallBack3(unsigned int nMsgType, uint8_t num);//异常回调
    void Camera1ExceptionCallBack4(unsigned int nMsgType, uint8_t num);//异常回调
    void Camera1ExceptionCallBack5(unsigned int nMsgType, uint8_t num);//异常回调

    /// <summary>
    /// 华睿智能相机
    /// </summary>
private:
    void*                       Hua1_h[MaxDeviceNum];           //设备句柄 
    unsigned int                C3_index[MaxDeviceNum];         //指定标识符
    CString                     C3_Ip[MaxDeviceNum]{ 0 };       //相机IP
    bool                        C3_bPro[MaxDeviceNum];
    void DaHua1_CamStart();      //打开华睿相机  
    void DaHua1_CamStop();         //关闭华睿智能相机 
    int JpgDecompress(IN OUT const unsigned char* Data, unsigned long Len, unsigned char* OutData, unsigned long OutLen, int Width, int Height);
    int DrawImg(void* hWnd, unsigned char* Data, unsigned int Len, unsigned int Width, unsigned int Height, int WndWidth, int WinHeight);
    void DaHuaDisplay(void* hWnd, const VslbRunResult* results, CString Bandwidth, BOOL NetMbps, int TrayNo, int DivideTop);
    void DaHuaDisplay1(void* hWnd, RunResult results, CString Bandwidth, BOOL NetMbps, int TrayNo, int Divide);    //显示图像
    void DaHuaDisplay2(void* hWnd, RunResult results, CString Bandwidth, BOOL NetMbps, int TrayNo, int Divide);    //显示图像 
    void DaHua1_GetParameter();//华睿智能相机参数获取
    void DaHua1_SetParameter();//华睿智能相机参数设置 
public:
    void AllCameraCodeInfoC0(const AllCameraCodeInfo* allCameraInfo);    /***********1 包裹包裹所有相机信息回调函数**************/
    void IpcCombineInfoC0(const VslbIpcCombineResult* ipcCombineInfo);   /***********2 包裹全景相机信息回调函数**************/
    void RunResultC0(const char* key, const VslbRunResult* pstOutput);     /***********3 主回调信息处理**************/ 
    void CamDisconnectC0(const VslbCameraTags* cameraKey);  //相机上线离线回调
    void ProcRealImageCB(const VslbImage* img);//相机图像实时回调
    void HuaDisplay();

    /// <summary>
    /// 中科微至相机
    /// </summary>
public:
    void zhong_wei_quick_scan_system_state(bool state, void* userData);
    void Zk0_SetTiggerMode();//初次打开中科相机时，触发模式设置
    //注册扫码系统状态回调函数
    void Zk0_GetParameter(uint8_t state);                               //中微参数0=设置1=获取
    void Zk0_SetParameter(uint8_t state);                               //中微参数0=设置1=获取
    void zhong_wei_result(QuickScanPackageInfo* pstOutput);                //注册扫码结果回调函数
    void ZhongWei_Result0(QuickScanPackageInfo* pstOutput, uint8_t num);   //扫码处理结果
    void ZhongWei_Result1(QuickScanPackageInfo* pstOutput, uint8_t num);   //扫码处理结果
    void ZhongWei_Result2(QuickScanPackageInfo* pstOutput, uint8_t num);   //扫码处理结果
    void ZhongWei_Result3(QuickScanPackageInfo* pstOutput, uint8_t num);   //扫码处理结果
    void ZhongWei_Result4(QuickScanPackageInfo* pstOutput, uint8_t num);   //扫码处理结果
    void ZhongWei_Result5(QuickScanPackageInfo* pstOutput, uint8_t num);   //扫码处理结果
    void zhong_wei_camera_state(const char* name, int len, bool state, void* userData);  //注册相机状态回调函数 
    void ZhongWei0_CamStart();  //中科微至相机读码
    void DisplayZw(uint8_t num, int16_t all_time, void* hWnd, QuickScanPackageInfo* pstOutput, CString Bandwidth, BOOL NetMbps, string dis_text, uint8_t emSize, int DivideTop, string* state);
    CString strFoldLeft,strFoldRight;    //折叠右侧标志
    bool CheckNoreadText;//勾选识别率显示
    bool CheckLocalTime=0;//时间显示勾选
    afx_msg void OnBnClickedBtnfoldright();//折叠右侧按钮
    void FoldRight();   //折叠右侧
    void FoldLeft();   
    
private: 
    uint16_t ImageNumber=0;       //帧号
    void packageUpData(std::string  data, std::string  msg_type);//打包数据格式 
public:
    void PostWriteCallback(const char* buffer, size_t size, size_t nmemb, void* userp);
    afx_msg void OnMove(int x, int y);
    afx_msg void OnBnClickedPrintscheck();
    void http1_Connect();    //HTTP传图
    bool Http1_Send(char*  data, unsigned int len,  char* msg_type);    //HTTP传图
    void http1_callbacks(const boost::system::error_code& error,   std::size_t bytes_transferred);
    afx_msg void OnBnClickedButton1();
private:
    string          t_c_Type;
    string          t_c_Type2;
    uint16_t        BindingTime=200;
    uint16_t        NoBindingTime = 200;
    int             BindingDelayTime = -80;
    int16_t         t_binding    =0; //绑定时间
    int16_t         t_bindingNext=0; //下个盘的绑定时间
    bool            tcpImgBinding;   //发送绑定结果里需要图片长度
    mutex           mtx_BindingImage;   //条码tcp存图
public:
    void PredictionTray();//预测托盘
    void TrayAndCode();
    //托盘绑定条码
    void h_Tcp6(const boost::system::error_code& error, std::size_t bytes_transferred);
    void h_Tcp5(const boost::system::error_code& error, std::size_t bytes_transferred);
    void h_Tcp7(const boost::system::error_code& error, std::size_t bytes_transferred);
    void RunTcp7();
    void RunTcp5();
    //接收TCP  6
    void RunTcp6();//打开TCP  6 
    
    afx_msg void OnBnClickedCheckprint1(); //界面输出
    afx_msg void OnBnClickedCheckprint2(); //界面输出
    afx_msg void OnBnClickedCheckprint3(); //界面输出
    afx_msg void OnBnClickedCheckprint4(); //界面输出
    afx_msg void OnCbnSelendokCombo1Parameter();
    afx_msg void OnBnClickedChecknoread();
    afx_msg void OnEndSession(BOOL bEnding);
    afx_msg void OnBnClickedBtnfoldleft();
    afx_msg void OnCbnSelendokLightcontrol();
    afx_msg void OnCbnSelendokBurstmode();
    HANDLE StartProcess(LPCTSTR program, LPCTSTR args);//窗口控件中嵌入第三方exe程序
    void RunThirdExe();//窗口控件中嵌入第三方exe程序

    afx_msg void OnCbnSelendokLineselector();
    afx_msg void OnBnClickedCheckprint5();
    afx_msg void OnMoving(UINT fwSide, LPRECT pRect);
    afx_msg void OnWindowPosChanged(WINDOWPOS* lpwndpos);
    afx_msg void OnBnClickedChecklocaltime();
    afx_msg void OnCbnSelendokCombocodetype();
    afx_msg void OnBnClickedCheckHex1();
    afx_msg void OnBnClickedCheckHex2();
    afx_msg void OnBnClickedCheckHex3();
    afx_msg void OnBnClickedCheckHex4();
    afx_msg void OnBnClickedBtnfoldlift();
    void OnBnClickedCheckconsoleoutput();
    protected:
        bool m_bConsoleOpen; 
        HWND g_hWndConsole = NULL;
public:
    afx_msg void OnNMDblclkListprint1(NMHDR* pNMHDR, LRESULT* pResult);
    afx_msg void OnNMClickListprint1(NMHDR* pNMHDR, LRESULT* pResult);
    afx_msg void OnEnKillfocusEdit1List();
    afx_msg void OnCbnSelendokLineouthardtriggeractive();
};

